﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using app.Models;
using AmuTools;

namespace app.Api
{
    /*
     * 投融资对接
    */
    public class ApiAbutment : ApiBase
    {
        public ApiAbutment(Controller ctx) : base(ctx) { }

        #region 自定义请求参数
        int req_demand_member_id { get { return GetIntParam(new ReqIntParamOption { Name = "demand_member_id" }); } }
        int req_service_member_id { get { return GetIntParam(new ReqIntParamOption { Name = "service_member_id" }); } }
        int req_demand_id { get { return GetIntParam(new ReqIntParamOption { Name = "demand_id" }); } }
        int req_service_id { get { return GetIntParam(new ReqIntParamOption { Name = "service_id", Level = REQPARAMLEVEL.FREE }); } }
        string req_self_role { get { return GetStringParam(new ReqStringParamOption { Name = "self_role" }); } }

        #endregion

        public void Do(string action)
        {
            // 全局上控制，此函数下的所有接口都是仅供管理员和会员访问的
            if (UserIdentity != IDENTITY.ADMIN && UserIdentity != IDENTITY.MEMBER) ThrowStatus(STATUS.NO_PERMISSION);

            switch (action)
            {
                case "get":
                    {
                        Cd cd = new Cd("id={0}", req_id);
                        if (UserIdentity == IDENTITY.MEMBER)
                        { // 如果是会员，必须是对接的某一方才能访问
                            cd.And("demand_member_id={0} or service_member_id={0}", UserCode);
                        }
                        Abutment abutment = G.DB.Get<Abutment>(cd.Render()).GetFirstEntity();
                        ResponseJson(new ObjectResult { data = abutment});
                        break;
                    }
                case "butted":
                    {
                        ResponseJson(GetPageResult<Abutment>(GetConditionStr(), "create_time desc"), "number,id,title,demand_enterprise,service_enterprise,demand_name,service_name,demand_status,service_status,step_abutment_data,create_time");
                        break;
                    }
                case "receive_list":
                    {
                        ResponseJson(GetPageResult<Abutment>(GetConditionStr(SEND_DIRECTION.Receive), "create_time desc"), "number,id,title,demand_enterprise,service_enterprise,demand_name,service_name,demand_status,service_status,process,create_time");
                        break;
                    }
                case "deliver_list":
                    {
                        ResponseJson(GetPageResult<Abutment>(GetConditionStr(SEND_DIRECTION.Deliver), "create_time desc"), "number,id,title,demand_enterprise,service_enterprise,demand_name,service_name,demand_status,service_status,process,create_time");
                        break;
                    }
                case "is_bindings":
                    {
                        string demand_id = GetStringParam(new ReqStringParamOption { Name = "demand_id" , Level = REQPARAMLEVEL.FREE });
                        string service_id = GetStringParam(new ReqStringParamOption { Name = "service_id" , Level = REQPARAMLEVEL.FREE });
                        string demand_member_id = GetStringParam(new ReqStringParamOption { Name = "demand_member_id", Level = REQPARAMLEVEL.FREE });
                        string service_member_id = GetStringParam(new ReqStringParamOption { Name = "service_member_id", Level = REQPARAMLEVEL.FREE });

                        if (demand_member_id == "") demand_member_id = UserCode;
                        else if (service_member_id == "") service_member_id = UserCode;
                        if (demand_member_id != "" && service_member_id != "")
                        {
                            if (demand_member_id == service_member_id)
                            {
                                ResponseJson(new BooleanResult { value = false, message = "无法与本人对接" });
                            }
                            else
                            {
                                Member m = G.DB.GetById<Member>(UserCode);
                                if (demand_id != "")
                                {
                                    
                                    if (m.role_type != 5)//5,服务机构
                                    {
                                        ResponseJson(new BooleanResult { value = false,message="您的身份不是服务机构，无法请求需求。" });
                                    }
                                    else
                                    {
                                        Cd cd = new Cd();
                                        cd.And("service_member_id = '{0}'", UserCode);
                                        cd.And("demand_id = '{0}'", demand_id);
                                        if (G.DB.GetCount<Abutment>(cd.Render()) > 0)
                                        { 
                                            ResponseJson(new BooleanResult { value = false, message = "已对接此项目！" });
                                        }
                                        else
                                        {
                                            ResponseJson(new BooleanResult { value = true });
                                        }
                                    }
                                    
                                }
                                else if (service_id != "")
                                {
                                    if(m.role_type == 5)
                                    {
                                        ResponseJson(new BooleanResult { value = false, message = "您的身份是服务机构，无法请求服务。" });
                                    }
                                    else
                                    {
                                        Cd cd = new Cd();
                                        cd.And("demand_member_id = '{0}'", UserCode);
                                        cd.And("service_id = '{0}'", service_id);
                                        if (G.DB.GetCount<Abutment>(cd.Render()) > 0)
                                        {
                                            ResponseJson(new BooleanResult { value = false, message = "已对接此项目！" });
                                        }
                                        else
                                        {
                                            ResponseJson(new BooleanResult { value = true });
                                        }
                                    }
                                    
                                }
                            }
                        }
                        else
                        {
                            ResponseJson(new BooleanResult { value = false, message = "你正在进行非法操作，请正确登陆本网站！" });
                        }
                        
                        break;
                    }
                case "bindings":
                    {
                        string sponsor = GetStringParam(new ReqStringParamOption { Name = "sponsor" });
                        int demand_member_id = GetIntParam(new ReqIntParamOption { Name = "demand_member_id" , Level = REQPARAMLEVEL.FREE });
                        int service_member_id = GetIntParam(new ReqIntParamOption { Name = "service_member_id" , Level = REQPARAMLEVEL.FREE});
                        int demand_id = GetIntParam(new ReqIntParamOption { Name = "demand_id" , Level = REQPARAMLEVEL.FREE });
                        int service_id = GetIntParam(new ReqIntParamOption { Name = "service_id" , Level = REQPARAMLEVEL.FREE });
                        string title = GetStringParam(new ReqStringParamOption { Name = "title" });
                        string description = GetStringParam(new ReqStringParamOption { Name = "description" });
                           
                        if (demand_member_id == 0) demand_member_id = int.Parse(UserCode);
                        else if (service_member_id == 0) service_member_id = int.Parse(UserCode);
                        
                        Abutment ab = new Abutment();
                        ab.title = title;
                        ab.description = description;
                        ab.sponsor = sponsor;
                        ab.demand_member_id = demand_member_id;
                        ab.demand_enterprise = G.DB.GetById<Member>(demand_member_id).enterprise_name;
                        ab.demand_id = demand_id;
                        if (demand_id != 0) {
                            ab.demand_name = G.DB.GetById<DemandItem>(demand_id).title;
                        }
                        ab.service_member_id = service_member_id;
                        ab.service_enterprise = G.DB.GetById<Member>(service_member_id).enterprise_name;
                        ab.service_id = service_id;
                        string number = "am" + DateTimeEx.GetNowTimeStamp() + ab.service_member_id + ab.demand_member_id;
                        ab.number = number;
                        if (service_id != 0)
                        {
                            ab.service_name = G.DB.GetById<ServiceItem>(service_id).title;
                        }
                        //为了在前台显示时间加上的
                        ab.create_time = DateTimeEx.DateTimeToTimeStamp(DateTime.Now);
                        if (sponsor == "provider") ab.service_status = (int)ABUTMENT_STATUS.INTERVIEW;
                        if (sponsor == "demander") ab.demand_status = (int)ABUTMENT_STATUS.INTERVIEW;
                        ResponseJson(new BooleanResult { value = G.DB.Insert<Abutment>(ab) > 0 });
                        //新增的消息提醒
                        if (sponsor == "provider") {
                            SendMessage(ab.demand_member_id,"您有新的约谈！","您有一个服务机构：【"+ab.service_member.enterprise_name+"】发起的约谈,标题为【"+ab.title+"】");
                            MesHelper.SendServiceRequestDemandMes(ab.demand_member.mobile_phone);
                        }
                        if (sponsor == "demander") {
                            SendMessage(ab.service_member_id, "您有新的投递！", "您有一个企业：【" + ab.demand_member.enterprise_name + "】发起的投递,标题为【" + ab.title + "】");
                            MesHelper.SendServiceRequestDemandMes(ab.service_member.mobile_phone);
                        }
                        break;
                    }
                case "begin":
                    {
                        Abutment abutment = new Abutment { demand_id = req_demand_id, service_id = req_service_id };
                        if (abutment.service_member_id == int.Parse(UserCode))
                        {
                            abutment.service_member_id = int.Parse(UserCode);
                            abutment.demand_member_id = req_demand_member_id;
                            abutment.service_status = (int)ABUTMENT_STATUS.AGREE;
                            abutment.demand_status = (int)ABUTMENT_STATUS.AGREE;
                        }
                        else if (abutment.demand_member_id == int.Parse(UserCode))
                        {
                            abutment.service_member_id = req_service_member_id;
                            abutment.demand_member_id = int.Parse(UserCode);
                            abutment.demand_status = (int)ABUTMENT_STATUS.AGREE;
                            abutment.service_status = (int)ABUTMENT_STATUS.AGREE;
                        }
                        G.DB.Insert<Abutment>(abutment);
                        ResponseJson(new Result());
                        break;
                    }
                case "agree":
                    {
                        Abutment abutment = G.DB.GetById<Abutment>(req_id);
                        Member demand_member = abutment.demand_member;
                        Member service_member = abutment.service_member;
                        // 改变状态
                        if (abutment.service_member_id == int.Parse(UserCode))
                        {
                            if((ABUTMENT_STATUS)abutment.demand_status == ABUTMENT_STATUS.AGREE && (ABUTMENT_STATUS)abutment.service_status == ABUTMENT_STATUS.NONE)
                            { 
                                abutment.service_status = (int)ABUTMENT_STATUS.AGREE;
                                SendMessage(abutment.demand_member_id, "服务机构：【" + abutment.service_member.enterprise_name + "】已经同意了合作！", "服务机构：【" + abutment.service_member.enterprise_name + "】已经同意了您的标题为【" + abutment.title + "】的合作！");
                            }
                            else if ((ABUTMENT_STATUS)abutment.service_status == ABUTMENT_STATUS.AGREE)
                            {
                                abutment.service_status = (int)ABUTMENT_STATUS.FINISH;
                                SendMessage(abutment.demand_member_id, "服务机构：【" + abutment.service_member.enterprise_name + "】已经结束了合作！", "服务机构：【" + abutment.service_member.enterprise_name + "】已经结束了您的标题为【" + abutment.title + "】的合作！");
                            }
                        }
                        else if (abutment.demand_member_id == int.Parse(UserCode))
                        {
                            if ((ABUTMENT_STATUS)abutment.service_status == ABUTMENT_STATUS.AGREE && (ABUTMENT_STATUS)abutment.demand_status == ABUTMENT_STATUS.NONE)
                            {
                                abutment.demand_status = (int)ABUTMENT_STATUS.AGREE;
                                SendMessage(abutment.service_member_id, "企业：【" + abutment.demand_member.enterprise_name + "】已经同意了合作！", "企业：【" + abutment.demand_member.enterprise_name + "】已经同意了您的标题为【" + abutment.title + "】的合作！");
                            }
                            else if ((ABUTMENT_STATUS)abutment.demand_status == ABUTMENT_STATUS.AGREE)
                            {
                                abutment.demand_status = (int)ABUTMENT_STATUS.FINISH;
                                SendMessage(abutment.service_member_id, "企业：【" + abutment.demand_member.enterprise_name + "】已经结束了合作！", "企业：【" + abutment.demand_member.enterprise_name + "】已经结束了您的标题为【" + abutment.title + "】的合作！");
                            }
                        }
                        // 如果合作成功完成，企业和服务机构成功数都加1
                        if((ABUTMENT_STATUS)abutment.demand_status == ABUTMENT_STATUS.FINISH && (ABUTMENT_STATUS)abutment.service_status == ABUTMENT_STATUS.FINISH)
                        {
                            demand_member.success_count += 1;
                            service_member.success_count += 1;
                        }
                        // 如果有一方确认合作完成，则评价
                        double rate = GetDoubleParam(new ReqDoubleParamOption { Name = "rate", Level = REQPARAMLEVEL.FREE });
                        string reason = GetStringParam(new ReqStringParamOption { Name = "reason", Level = REQPARAMLEVEL.FREE });
                        if ((ABUTMENT_STATUS)abutment.demand_status == ABUTMENT_STATUS.FINISH && abutment.demand_member_id == int.Parse(UserCode))
                        {
                            //新添加的计算平均分部分
                            Member member = abutment.service_member;
                            if (member.success_count <= 1)
                            {
                                member.rate = rate;
                            }
                            else
                            {
                                member.rate = (member.rate * (member.success_count-1) + rate) / member.success_count;
                            }
                            abutment.serviceReason = reason;
                            abutment.serviceRate = rate;
                        }
                        else if ((ABUTMENT_STATUS)abutment.service_status == ABUTMENT_STATUS.FINISH && abutment.service_member_id == int.Parse(UserCode)) {
                            //新添加的计算平均分部分
                            Member member = abutment.demand_member;
                            if (member.success_count <= 1)
                            {
                                member.rate = rate;
                            }
                            else
                            {
                                member.rate = (member.rate * (member.success_count-1) + rate) / member.success_count;
                            }
                            abutment.demandReason = reason;
                            abutment.demandRate = rate;
                            abutment.contract_ids = GetStringParam(new ReqStringParamOption { Name = "contract_ids" });
                        }
                        G.DB.Update<Member>(demand_member);
                        G.DB.Update<Member>(service_member);
                        G.DB.Update<Abutment>(abutment);
                        ResponseJson(new Result());
                        break;
                    }
                case "cancel":
                    {
                        Abutment abutment = G.DB.GetById<Abutment>(req_id);
                        abutment.refuse_reason = GetStringParam(new ReqStringParamOption { Name = "refuse_reason" });
                        if (abutment.service_member_id == int.Parse(UserCode))
                        {
                            abutment.service_status = (int)ABUTMENT_STATUS.CANCEL;
                            SendMessage(abutment.demand_member_id,"服务机构：【" + abutment.service_member.enterprise_name + "】已取消与您的对接！", "您的标题为【"+ abutment.title+ "】的对接已被服务机构：【" + abutment.service_member.enterprise_name + "】取消。");
                        }
                        else if (abutment.demand_member_id == int.Parse(UserCode))
                        {
                            abutment.demand_status = (int)ABUTMENT_STATUS.CANCEL;
                            SendMessage(abutment.service_member_id, "企业：【" + abutment.demand_member.enterprise_name + "】已取消与您的对接！", "您的标题为【" + abutment.title + "】的对接已被企业：【" + abutment.demand_member.enterprise_name + "】取消。");
                        }
                        G.DB.Update<Abutment>(abutment);
                        ResponseJson(new Result());
                        break;
                    }
                default: break;
            }
        }

        private string GetConditionStr(string direction = "")
        {
            // 收到的投递：当前为服务方，发起者为需求方，会员id为自己
            // 收到的约谈：当前为需求方，发起者为服务方，会员id为自己
            // 发起的约谈：当前为服务方，发起者为服务方，会员id为自己
            // 收到的约谈：当前为需求方，发起者为需求方，会员id为自己
            // 1最新消息，2正在约谈，3已达成，4已完成，5已取消, 6已拒绝
            string status_format = "";
            string status_str = "";
            string userid_str = "";
            string condition_str = "";
            string sponsor_str = "";
            if (req_self_role == SPONSOR_TYPES.Provider)
            {
                if(direction == SEND_DIRECTION.Receive)
                {
                    sponsor_str = string.Format(" and sponsor = '{0}'", SPONSOR_TYPES.Demander);
                    status_format = " and service_status = {0}";
                }
                else if(direction == SEND_DIRECTION.Deliver)
                {
                    sponsor_str = string.Format(" and sponsor = '{0}'", SPONSOR_TYPES.Provider);
                    status_format = " and demand_status = {0}";
                }
                userid_str = string.Format("service_member_id = '{0}'", UserCode);
                
            }
            else if (req_self_role == SPONSOR_TYPES.Demander)
            {
                if (direction == SEND_DIRECTION.Receive)
                {
                    sponsor_str = string.Format(" and sponsor = '{0}'", SPONSOR_TYPES.Provider);
                    status_format = " and demand_status = {0}";
                }
                else if (direction == SEND_DIRECTION.Deliver)
                {
                    sponsor_str = string.Format(" and sponsor = '{0}'", SPONSOR_TYPES.Demander);
                    status_format = " and service_status = {0}";
                }
                userid_str = string.Format("demand_member_id = '{0}'", UserCode);


            }
            else
            {
                ThrowStatus(STATUS.NO_RESOURCES, "没有符合当前身份角色的数据！");
            }
            switch (req_status)
            {
                case 1: status_str = string.Format(status_format, (int)ABUTMENT_STATUS.NONE); break; //新的投递,新的约谈
                case 2: status_str = string.Format(" and ((demand_status = {0} and service_status = {1}) or (service_status = {0} and demand_status = {1})or (service_status = {0} and demand_status = {0}) )", (int)ABUTMENT_STATUS.INTERVIEW, (int)ABUTMENT_STATUS.AGREE); break;
                    //正在约谈
                case 3: status_str = string.Format(" and ((demand_status = {0} and service_status = {1}) or (service_status = {0} and demand_status = {1}) or (service_status = {0} and demand_status = {0}))", (int)ABUTMENT_STATUS.AGREE, (int)ABUTMENT_STATUS.FINISH); break;
                    //正在合作
                case 4: status_str = string.Format(" and (demand_status = {0} and service_status = {0})", (int)ABUTMENT_STATUS.FINISH); break;
                    //合作完成
                case 5: status_str = string.Format(" and (demand_status = {0} or service_status = {0}) and demand_status <> {1} and service_status <> {1}", (int)ABUTMENT_STATUS.CANCEL, (int)ABUTMENT_STATUS.NONE); break;
                    //取消合作
                case 6: status_str = string.Format(" and (demand_status = {0} or service_status = {0}) and (demand_status = {1} or service_status = {1})", (int)ABUTMENT_STATUS.CANCEL, (int)ABUTMENT_STATUS.INTERVIEW); break;
                //取消约谈
                case 7: status_str = string.Format(" and demand_status >= 1 and service_status >= 1"); break;
            }
            condition_str = userid_str + status_str + sponsor_str;
            return condition_str;
        }
    }


}